package com.wyz.saas.common.base

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.atom.api.ApiContext
import com.atom.module.mvvm.base.AbstractFragment
import com.atom.module.mvvm.base.IViewModel
import com.wyz.saas.api.common.ActivityApi
import com.wyz.saas.api.common.FragmentApi
import com.wyz.saas.common.R
import com.wyz.saas.common.view.EmptyView

abstract class AbstractApiFragment<V : ViewDataBinding, VM : AbstractApiViewModel<*>> :
    AbstractFragment<V, VM>(), FragmentApi.OnBackPressedListener {

    private val TAG = javaClass.name
    protected var mPlaceHolderView: EmptyView? = null
    protected var mIsFirstInitData = true

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (mIsFirstInitData) {
            mIsFirstInitData = false
            onFirst()
        }
    }

    override fun initViewBinding(binding: V?, viewModel: VM?) {
        super.initViewBinding(binding, viewModel)
        mPlaceHolderView = binding?.root?.findViewById(R.id.tag_empty_view)
    }

    protected open fun onFirst() {}

    open fun apiContext(): ApiContext {
        if (activity is ActivityApi) {
            return (activity as ActivityApi).apiContext()
        }
        throw RuntimeException("Your Activity can't instanceof ActivityApi!")
    }

    protected open fun reportException(ex: Exception?) {
        apiContext().report(TAG, ex)
    }

    override fun onBackPressed(): Boolean {
        return false
    }

    protected open fun loadFragment(
        fragment: Fragment,
        addToBackStack: Boolean
    ) {
        val activity = this.activity
        if (activity is FragmentApi) {
            activity.loadFragment(fragment, addToBackStack)
        }
    }

    protected open fun backFragment() {
        this.fragmentManager?.popBackStack()
    }

    fun showError(strRes: Int) {
        showError(resources.getString(strRes))
    }

    @SuppressLint("ShowToast")
    fun showError(strError: String) {
        mPlaceHolderView
            ?.triggerError(strError)
            ?: also {
                apiContext().toast(strError)
            }
    }

    fun showLoading() {
        mPlaceHolderView?.triggerLoading()
    }

    fun hideLoading() {
        mPlaceHolderView?.triggerOk()
    }
}